package cn.hist.hfp.controller;

import cn.hist.hfp.service.AuthService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.ManagerLoginVO;
import cn.hist.hfp.vo.UserLoginVO;
import cn.hist.hfp.vo.ValidationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final
    AuthService authService;

    private final
    Authentication authentication;

    private final MyResponse<ValidationVO> myResponse;

    @Autowired
    public AuthController(AuthService authService, Authentication authentication, MyResponse<ValidationVO> myResponse) {
        this.authService = authService;
        this.authentication = authentication;
        this.myResponse = myResponse;
    }

    @PostMapping
    public ResponseEntity<ValidationVO> userLogin(@RequestBody UserLoginVO loginVO) {
        ValidationVO validationVO = authService.userLogin(loginVO);
        return myResponse.response(201, validationVO.getToken(), validationVO);
    }

    @DeleteMapping
    public ResponseEntity<ValidationVO> userLogout(@RequestBody ValidationVO validationVO) {
        return myResponse.response(200, "", authService.userLogout(validationVO));
    }

    @PostMapping("/re")
    public ResponseEntity<ValidationVO> updateToken(@RequestHeader String token) {
        if (token == null || token.equals("") || token.equals("null")) {
            return myResponse.response(200, "", new ValidationVO());
        }

        String newToken = authentication.refreshToken(token);
        return myResponse.response(200, newToken, authService.reLogin(newToken));
    }

    @PostMapping("/manager")
    public ResponseEntity<ValidationVO> managerLogin(@RequestBody ManagerLoginVO loginVO) {
        ValidationVO managerValidationVO = authService.managerLogin(loginVO);
        MyResponse<ValidationVO> myResponse = new MyResponse<>();
        System.out.println(managerValidationVO.getToken());
        return myResponse.response(201, managerValidationVO.getToken(), managerValidationVO);
    }

    @DeleteMapping("/manager")
    public ResponseEntity<ValidationVO> managerLogout(@RequestBody ValidationVO validationVO) {
        MyResponse<ValidationVO> myResponse = new MyResponse<>();
        return myResponse.response(200, "", authService.managerLogout(validationVO));
    }
}
